<?php

    include("header.php");

    setTabIndex(2);

    createPage("Liga - Zilveren Toren");

?>

<?php

  	$connect = mysql_connect(DB_SERVER, DB_USER, DB_PWD);

	mysql_select_db(DB_CATALOG);



	$dep = $_GET['dep'];

	$crosstableMap = array();



	$query = sprintf("select count(*) as nrOfRounds from zt_team te

    join zt_tournament t on t.tournament_id = te.tournament_id

	join zt_group g on g.group_id = te.group_id

    where g.group_name = '%s' and t.iscurrent = 1",

    $dep);

  	$roundsResult = mysql_query($query, $connect);

  	rejectIfError($query, "view_crosstable.php: selecteren van aantal ronden is mislukt.");

  	$row = mysql_fetch_assoc($roundsResult);

  	$nrOfRounds = $row['nrOfRounds'];

    

    $hoverwriteBoardResult = "";

    $voverwriteBoardResult = "";

    $currentGame = "";

    $query = sprintf("select g.*, ht.team_id AS hit, ht.team_name, ht.team_nr, vt.team_id AS vit, vt.team_name, vt.team_nr
    
        from zt_game g join zt_calendar c on

        c.calendar_id = g.calendar_id join zt_tournament t on

        c.tournament_id = t.tournament_id join zt_group gr

        on gr.group_id = g.group_id 
        
        JOIN zt_team ht ON ht.team_id = g.home_team 

        JOIN zt_team vt ON vt.team_id = g.visit_team
        
        where t.iscurrent = 1

        and gr.group_name = '%s'", $dep);

    $gameResult = mysql_query($query, $connect);

    rejectTranIfError($query, "calculate_stats.php: selecteren van de partijen is mislukt.");

    $minBoards = 2;
    if ( strnatcasecmp($dep, '1') == 0 ) $minBoards = 3;
    
    $htForfait = array();
    $vtForfait = array();
    
    $htTournamentForfait = array();
    $vtTournamentForfait = array();    

    if (mysql_num_rows($gameResult) > 0) {

        while ($gameRow = mysql_fetch_assoc($gameResult)) {
            
            $query = "SELECT board_nr,index_nr_home,index_nr_visit FROM zt_game_player gp WHERE gp.game_id = ".$gameRow['game_id'];
            $boardResult = mysql_query($query, $connect);
            rejectTranIfError($query, "calculate_stats.php: selecteren van de partijdetails is mislukt.");
            while ($boardRow = mysql_fetch_assoc($boardResult)) {
                $boardnr = $boardRow['board_nr'];
                $hindex = $boardRow['index_nr_home'];
                $vindex = $boardRow['index_nr_visit'];
                if ($boardnr <= $minBoards) {
                    if ($hindex == 0) {
                        $htForfait[$gameRow['game_id']] = 1;
                    }
                    if ($vindex == 0) {
                        $vtForfait[$gameRow['game_id']] = 1;   
                    }       
                }
            }
            
            // lookup decided tournament forfait for team
        
            $hit = $gameRow['hit'];
            $vit = $gameRow['vit'];
            
            $query = "SELECT count(1) forfaited FROM zt_team_forfait WHERE team_id = ".$hit;
            $forfaitResult = mysql_query($query, $connect);
            $forfaitRow = mysql_fetch_assoc($forfaitResult);
            if ($forfaitRow["forfaited"] == 1) {
                 $htTournamentForfait[$gameRow['game_id']] = 1;                
            }   
            
            $query = "SELECT count(1) forfaited FROM zt_team_forfait WHERE team_id = ".$vit;
            $forfaitResult = mysql_query($query, $connect);
            $forfaitRow = mysql_fetch_assoc($forfaitResult);
            if ($forfaitRow["forfaited"] == 1) {
                $vtTournamentForfait[$gameRow['game_id']] = 1;  
            }
            
        }        
        
    }
                            
	$query = sprintf("select g.game_id, zgp.game_player_id, c.round_nr, zgp.board_nr,

	  	ht.team_name as thuisploeg, ht.club_id as htclub,

	    htp.bp as htbp, htp.mp as htmp, htp.games_played as htcount,

	  	vt.team_name as bezoekers, vt.club_id as vtclub,

	    vtp.bp as vtbp, vtp.mp as vtmp, vtp.games_played as vtcount,

	  	zgp.result_type_id, zgp.home_error_id, zgp.visit_error_id

	    from zt_game_player zgp join zt_game g on g.game_id = zgp.game_id

	    join zt_calendar c on c.calendar_id = g.calendar_id

	    join zt_tournament t on c.tournament_id = t.tournament_id

	    join zt_group gr on gr.group_id = g.group_id

	    join zt_team ht on ht.team_id = g.home_team

	    join zt_team_position htp on htp.team_id = ht.team_id

	    join zt_team vt on vt.team_id = g.visit_team

	    join zt_team_position vtp on vtp.team_id = vt.team_id

	    where t.iscurrent = 1 and gr.group_name = '%s'", $dep);

  	$dataRecord = mysql_query($query, $connect);

  	rejectIfError($query, "view_crosstable.php: selecteren van crosstable data records is mislukt.");

	while ($row = mysql_fetch_assoc($dataRecord)) {

        $gameId = $row['game_id'];
        
	    $record = new ZTCrossTableRecord();

	    $record->gameNr = $row['game_player_id'];

	    $record->roundNr = $row['round_nr'];

	    $record->boardNr = $row['board_nr'];

	    $record->homeTeam = $row['thuisploeg'];

	    $record->homeTeamNr = $row['htclub'];

	    $record->homeTeamBP = $row['htbp'];

	    $record->homeTeamMP = $row['htmp'];

	    $record->homeErrorId = $row['home_error_id'];

	    $record->homeTeamCount = $row['htcount'];

	    $record->visitTeam = $row['bezoekers'];

	    $record->visitTeamNr = $row['vtclub'];

	    $record->visitTeamBP = $row['vtbp'];

	    $record->visitTeamMP = $row['vtmp'];

	    $record->visitTeamCount = $row['vtcount'];

	    $record->visitErrorId = $row['visit_error_id'];        
        
	    $record->result = $row['result_type_id'];
        
        if ( array_key_exists($gameId,$htForfait) ) {
            $record->homeErrorId = 5;    
        }
        if ( array_key_exists($gameId,$htTournamentForfait) ) {
            $record->homeErrorId = 6;
            $record->visitErrorId = 6;
        }
        
        if ( array_key_exists($gameId,$vtForfait) ) {
            $record->visitErrorId = 5;    
        }
        if ( array_key_exists($gameId,$vtTournamentForfait) ) {
            $record->homeErrorId = 6;
            $record->visitErrorId = 6;    
        }
        
        // resetting the overwritten results when a new game is encountered

        if (strnatcasecmp($currentGame, ($row['thuisploeg']."-".$row['bezoekers']) ) != 0) {

            $hoverwriteBoardResult = "";

            $voverwriteBoardResult = "";

            $currentGame = $row['thuisploeg']."-".$row['bezoekers'];

        }



		$homeTeamResult = getParsedResult($record, true);

		$visitTeamResult = getParsedResult($record, false);


		calculateResults($record->homeTeam, $record->homeTeamNr, $record->visitTeam,

      	$record->visitTeamNr, $homeTeamResult, $record->homeTeamBP, $record->homeTeamMP,

      	$record->homeTeamCount);



    	calculateResults($record->visitTeam, $record->visitTeamNr, $record->homeTeam,

      	$record->homeTeamNr, $visitTeamResult, $record->visitTeamBP, $record->visitTeamMP,

      	$record->visitTeamCount);

	}



  	$crosstableResults = getSortedList($crosstableMap);



	function getSortedList($crosstableMap) {

	    $size = count($crosstableMap);

	    $duplicateMap = $crosstableMap;

	    $return = array();

	    	 

	    foreach($crosstableMap as $team1) {

	    	$rank = 0;

	      	foreach($duplicateMap as $team2) {

	        	if (strnatcasecmp($team1->teamName, $team2->teamName) != 0) {

	          		if ($team1->BP < $team2->BP) {

	            		$rank += 1;

	          		} else if ($team1->BP == $team2->BP) {

	            		if ($team1->MP < $team2->MP) {

	            			$rank += 1;

	            		} else if ($team1->MP == $team2->MP) {

	              			// totally equal, check if two teams played each other, let winner have prio

	              			//if (!empty($return[$rank])) {

	              				//$rank += 1;

	              			//}

	            		}

	          		}

	        	}

	      	}

	      	

	    	if (!empty($return[$rank])) {

	    		if (!empty($return[$rank+1])) {

	    			if (!empty($return[$rank+2])) {

		    			if (!empty($return[$rank+3])) {

		    				if (!empty($return[$rank+4])) {

		    					if (empty($return[$rank+5])) {

					    			$return[$rank+5] = $team1;

					    		}

				    		} else {

				    			$return[$rank+4] = $team1;

				    		}

			    		} else {

			    			$return[$rank+3] = $team1;

			    		}

	    			} else {

	    				$return[$rank+2] = $team1;

	    			}

	    		} else {

	    			$return[$rank+1] = $team1;

	    		}

	      	} else {

	      		$return[$rank] = $team1;	      		

	      	}

	      	

	    }

	    

	    return $return;

	}



	function getParsedResult($record, $isHomeTeam) {

		

		global $hoverwriteBoardResult;

        global $voverwriteBoardResult;

        

        $connect = mysql_connect(DB_SERVER, DB_USER, DB_PWD);

		mysql_select_db(DB_CATALOG);

		

		if ($isHomeTeam) {

            

            if (isset($record->homeErrorId) && $record->homeErrorId != 0) {

                $query = "select error_code from zt_game_player_error where error_id = ".$record->homeErrorId;

                $homeErrorResult = mysql_query($query, $connect);

                $homeErrorRow = mysql_fetch_assoc($homeErrorResult);

                $homeError = $homeErrorRow['error_code'];

                

                if (strnatcasecmp("invalid_order", $homeError) == 0) {

                    $record->result = 5;

                    //$hoverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("team_to_low", $homeError) == 0) {

                    $record->result = 5;

                    //$hoverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("wrong_team", $homeError) == 0) {

                    $record->result = 5;

                    //$hoverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("inherited_forfait", $homeError) == 0) {

                    $record->result = 5;

                    $hoverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("team_forfait", $homeError) == 0) {

                    $record->result = 5;

                    $hoverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("tournament_forfait", $homeError) == 0) {

                    $record->result = 6;

                    $hoverwriteBoardResult = $record->result;

                }

            } else if (isset($record->visitErrorId) && $record->visitErrorId != 0) {

                $query = "select error_code from zt_game_player_error where error_id = ".$record->visitErrorId;

                $visitErrorResult = mysql_query($query, $connect);

                $visitErrorRow = mysql_fetch_assoc($visitErrorResult);

                $visitError = $visitErrorRow['error_code'];

                

                if (strnatcasecmp("invalid_order", $visitError) == 0) {

                    $record->result = 4;

                } else if (strnatcasecmp("team_to_low", $visitError) == 0) {

                    $record->result = 4;

                } else if (strnatcasecmp("wrong_team", $visitError) == 0) {

                    $record->result = 4;

                } else if (strnatcasecmp("inherited_forfait", $visitError) == 0) {

                    $record->result = 4;
                    
                    $voverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("team_forfait", $visitError) == 0) {

                    $record->result = 4;
                    
                    $voverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("tournament_forfait", $visitError) == 0) {

                    $record->result = 6;
                    
                    $voverwriteBoardResult = $record->result;

                }

            }

            

            if ( !empty($hoverwriteBoardResult) ) {

                //$record->result = $hoverwriteBoardResult;

            } else if ( !empty($voverwriteBoardResult) ) {

                //$record->result = $voverwriteBoardResult;

            }

			

			switch ($record->result) {

			case 1:

				return 1.0;

			case 2:

				return 0.5;

			case 3:

				return 0.0;

			case 4:

				return 1.0;

			case 5:

				return 0.0;         

			case 6:

                return 0.0;

            }

		} else {

            

            if (isset($record->visitErrorId) && $record->visitErrorId != 0) {

                $query = "select error_code from zt_game_player_error where error_id = ".$record->visitErrorId;

                $visitErrorResult = mysql_query($query, $connect);

                $visitErrorRow = mysql_fetch_assoc($visitErrorResult);

                $visitError = $visitErrorRow['error_code'];

                

                if (strnatcasecmp("invalid_order", $visitError) == 0) {

                    $record->result = 4;

                    //$voverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("team_to_low", $visitError) == 0) {

                    $record->result = 4;

                    //$voverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("wrong_team", $visitError) == 0) {

                    $record->result = 4;

                    //$voverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("inherited_forfait", $visitError) == 0) {
                    
                    $record->result = 4;

                    $voverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("team_forfait", $visitError) == 0) {

                    $record->result = 4;

                    $voverwriteBoardResult = $record->result;

                }  else if (strnatcasecmp("tournament_forfait", $visitError) == 0) {

                    $record->result = 6;

                    $voverwriteBoardResult = $record->result;

                }

            } else if (isset($record->homeErrorId) && $record->homeErrorId != 0) {

                $query = "select error_code from zt_game_player_error where error_id = ".$record->homeErrorId;

                $homeErrorResult = mysql_query($query, $connect);

                $homeErrorRow = mysql_fetch_assoc($homeErrorResult);

                $homeError = $homeErrorRow['error_code'];

                

                if (strnatcasecmp("invalid_order", $homeError) == 0) {

                    $record->result = 5;

                } else if (strnatcasecmp("team_to_low", $homeError) == 0) {

                    $record->result = 5;

                } else if (strnatcasecmp("wrong_team", $homeError) == 0) {

                    $record->result = 5;

                } else if (strnatcasecmp("inherited_forfait", $homeError) == 0) {

                    $record->result = 5;
                    
                    $hoverwriteBoardResult = $record->result;

                } else if (strnatcasecmp("team_forfait", $homeError) == 0) {

                    $record->result = 5;
                    
                    $hoverwriteBoardResult = $record->result;

                }  else if (strnatcasecmp("tournament_forfait", $homeError) == 0) {

                    $record->result = 5;
                    
                    $hoverwriteBoardResult = $record->result;

                }

            }

            

            if ( !empty($voverwriteBoardResult) ) {

                //$record->result = $voverwriteBoardResult;

            } if ( !empty($hoverwriteBoardResult) ) {

                //$record->result = $hoverwriteBoardResult;

            } 

            

            switch ($record->result) {

			case 1:

				return 0.0;

			case 2:

				return 0.5;

			case 3:

				return 1.0;

			case 4:

				return 0.0;

			case 5:

				return 1.0;

			case 6:

                return 0.0;

            }

		}

	}



  	function calculateResults($homeTeam, $homeTeamNr, $visitTeam, $visitTeamNr, $result, $bp, $mp, $count) {



	    global $crosstableMap;

	

	    if ( !array_key_exists($homeTeam, $crosstableMap) ) {

			$gameResults = array();

			$gameResults[$visitTeam] = $result;

			$ctRow = new ZTCrossTableResult();

			$ctRow->results = $gameResults;

			$ctRow->total = $result;

			$ctRow->BP = $bp;

			$ctRow->MP = $mp;

			$ctRow->gameCount = $count;

	      	$ctRow->teamName = $homeTeam;

			$ctRow->teamNr = $homeTeamNr;

			$crosstableMap[$homeTeam] = $ctRow;

		} else {

	      	$ctRow = $crosstableMap[$homeTeam];

	      	$currentTotal = $ctRow->total;

			$newTotal = $currentTotal + $result;

			$ctRow->total = $newTotal;

			$gameResults = $ctRow->results;

			if ( !array_key_exists($visitTeam, $gameResults) ) {

				$gameResults[$visitTeam] = $result;

				$ctRow->results = $gameResults;

			} else {

				$currentResult = $gameResults[$visitTeam];

				$newResult = $currentResult + $result;

				$gameResults[$visitTeam] = $newResult;

				$ctRow->results = $gameResults;

			}

		}

	}



?>



<table height="100%" cellSpacing="0" cellPadding="0" width="100%" border="0" bgcolor="#FFFFFF">

	<tr>

		<td id="leftFiller" valign="top" height="100%" rowspan="3" bgcolor="#666666">

			<table border="0" cellpadding="0" cellspacing="0" height="100%" width="8px">

				<tr><td>&nbsp;</td></tr>

			</table>

		</td>

		<td id="header" valign="top" width="100%">

			<table border="0" width="100%" cellpadding="3" cellspacing="0" bgcolor="#10425b">
                <tr>
                    <td bgcolor="#666666" width="40%">
                        <?php include("inc_title.html"); ?>
                    </td>
                    <td bgcolor="#666666" align="right" valign="top">&nbsp;
                          <span class="headerSmall">Huidige versie PLAYER.DBF: <?=CURRENT_PLAYER_DBF?>
                        <?php
                        if (isset($user) && $user->club_id == 100) {
                        ?>
                        <br/>
                        <a class="headerSmall" href="import_player.php">laad andere versie</a>
                        <?php
                        }
                        ?>
                        </span>
                    </td>
                </tr>
            </table>
            <table align="center" border="0" width="100%" height="90%" cellpadding="0" cellspacing="0" style="border-top:#BCDD10 4px solid;">
                <tr>
                    <?php include("inc_sublinks.php"); ?> 
                </tr>

				<tr><td colspan="2" nowrap bgcolor="#BCDD10" height="4"><img src="../../../assets/images/spacer.gif" alt="" height="1" width="1"></td></tr>

				<tr>

					<td>&nbsp;</td>

					<td valign="top">

						<table align="left" cellspacing="10" width="100%">

							<tr>

								<td colspan="16">

									<span class="blackHeaderLarge">Zilveren Toren <?=CURRENT_ZT_YEAR?>

                  - Afdeling <?=$dep?> - Stand</span>

                  <br>&nbsp;<br>

                  <?php

                  $query = "select g.group_name from zt_group g join

		          	zt_tournament zt on zt.tournament_id = g.tournament_id

		            where zt.isCurrent = 1";

		          $result = mysql_query($query, $connect);

		          while ($row = mysql_fetch_assoc($result)) {

                  	$groupName = $row['group_name'];

                  ?>

                  <a class="quicklink" href="zt_department.php?dep=<?=$groupName?>">Afdeling <?=$groupName?></a>|</li>

                  <?php

                  }

                  ?>

                  <br>&nbsp;<br>

									<em>Opmerking : De partijuitslagen tonen de <strong>daadwerkelijke uitslag</strong>, wat

                                    niet noodzakelijk hetzelfde is als de gespeelde uitslag (omwille van forfaits).
                                    

								</td>

							</tr>

							<tr>

								<td>

									<table cellspacing="0" cellpadding="2" border="0" width="60%" align="center" style="border-style: solid ;border-width: thin">

										<tr>

										  <td width="10%" align="center"><strong>Rang</strong></td>

										  <td width="25%"><strong>Team</strong></td>

										  <td width="10%" align="center"><strong>Clubnr</strong></td>

  									<?php

  									for ($i = 0; $i < $nrOfRounds; $i++) {

  									?>

										  <td width="4%" align="center"><strong><?=$i+1?></strong></td>

										<?php

										}

										?>

										  <td width="5%" align="center"><strong>BP</strong></td>

										  <td width="5%" align="center"><strong>MP</strong></td>

										  <td width="5%" align="center"><strong>Aantal</strong></td>

										</tr>

										<?php

                    $size = count($crosstableResults);

                    

                    for ($i = 0; $i < $size; $i++) {

                    	if (!empty($crosstableResults[$i])) {

                    		

                    	

                    	$teamRow = $crosstableResults[$i];

                      	if ($i % 2 == 0) {

                  			$css = "clsTableData";

                  		} else {

                  			$css = "clsTableData2";

                  		}

										?>

										<tr class="<?=$css?>">

                    	<td align="center" class="crossTableCell"><strong><?=$i+1?></strong></td>

                    	<td class="crossTableCell"><?=$teamRow->teamName?></td style="crossTableCell">

                    	<td align="center" class="crossTableCell">&nbsp;&nbsp;<?=$teamRow->teamNr?></td>

                    <?php

                      for ($j = 0; $j < $nrOfRounds; $j++) {

                        if (array_key_exists($j, $crosstableResults)) {

                          $opponentRow = $crosstableResults[$j];



                          if (strnatcasecmp($teamRow->teamName, $opponentRow->teamName) == 0) {

                    ?>

                          <td style="background-color:#000000" class="crossTableCell">&nbsp;</td>

                    <?php

                          } else if ( array_key_exists($opponentRow->teamName, $teamRow->results) ) {

                            $matchRresult = $teamRow->results[$opponentRow->teamName];

                    ?>

                          <td align="center" class="crossTableCell"><?=$matchRresult?></td>

                    <?php

                          } else {

                    ?>

                          <td align="center" class="crossTableCell">&nbsp;</td>

                    <?php

                          }

                        } else {

                    ?>

                          <td align="center" class="crossTableCell">&nbsp;</td>

                    <?php

                        }

                      }

                    ?>

                    	<td align="center" class="crossTableCell"><?=$teamRow->BP?></td>

                    	<td align="center" class="crossTableCell"><?=$teamRow->MP?></td>

                    	<td align="center" class="crossTableCell"><?=$teamRow->gameCount?></td>

                    </tr>

                    <?php

						}

					}

                    ?>

									</table>

								</td>

							</tr>

							<?php

							if ($size == 0) {

							?>

  							<tr>

        					<td align="center" colspan="<?=$nrOfRounds+6?>"><strong>Nog geen resultaten ontvangen.</strong></td>

        				</tr>

        			<?php

        			}

        			?>

							<tr>

								<td align="center" colspan="4"><a href="zt_department.php?dep=<?=$dep?>"><img border="0" src="../../assets/images/24x24/shadow/arrow_left_green.gif"></a></td>

							</tr>

						</table>

					</td>

				</tr>

			</table>

		</td>

	</tr>

</table>



<?php include("footer.php"); ?>